package com.ah.proj.bus.user.dao;

import java.sql.SQLException;

import com.ah.proj.bean.User;
import com.ah.proj.util.BaseDao;

public class UserDao extends BaseDao {

	public boolean isUserExist(String username) {
		super.getConn();
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append("   id ");
		sb.append(" FROM ");
		sb.append("   user_info ");
		sb.append(" WHERE ");
		sb.append("   username=? ");
		try {
			super.psta = super.conn.prepareStatement(sb.toString());
			psta.setString(1, username);
			super.rs = psta.executeQuery();
			if (rs.next()) {
				// 若数据库中有数据
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			super.closeConn();
		}
		// 若数据库中没有数据
		return false;
	}

	public int register(User u) {
		super.getConn();
		StringBuffer sb = new StringBuffer();
		sb.append(" INSERT INTO ");
		sb.append("   user_info ");
		sb.append(" VALUES (null,?,?) ");// id传null，让系统自动生成
		try {
			super.psta = super.conn.prepareStatement(sb.toString());
			psta.setString(1, u.getUserName());
			psta.setString(2, u.getPwd());
			return psta.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			super.closeConn();
		}
		return -1;
	}

	public User login(User u) {
		super.getConn();
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append("   id, ");
		sb.append("   username ");
		sb.append(" FROM ");
		sb.append("   user_info ");
		sb.append(" WHERE ");
		sb.append("   username=? ");
		sb.append("   AND ");
		sb.append("   pwd=? ");
		try {
			super.psta = super.conn.prepareStatement(sb.toString());
			psta.setString(1, u.getUserName());
			psta.setString(2, u.getPwd());
			super.rs = psta.executeQuery();
			if (rs.next()) {
				// 若数据库中有数据，则用查出的数据填充u，并返回
				u.setId(rs.getInt(1));
				return u;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			super.closeConn();
		}
		// 若数据库中没有数据，返回null
		return null;
	}
}